<?php
namespace frontend\controllers;

use common\models\Category;
use common\utils\Com;
use yii\data\Pagination;
use yii\web\Controller;
use common\models\Article;
use yii\web\NotFoundHttpException;


class WordController extends BaseController{

    /**
     * 详情
     */
    public function actionIndex(){
        $id = \Yii::$app->request->get("id");
        $article = Article::findOne($id);
        if (empty($article)){
            return $this->redirect(Com::urlNews(2) , 301 );
        }elseif(!is_numeric($id)){
            return $this->redirect(Com::urlNews($article['id']) , 301 );
        }
        $cat = $article['cats'];
        if(empty($cat)){
            return $this->redirect(Com::urlCat(2) , 301 );
        }
        $list = Article::find()->select(['id','title'])->where(['>' ,'id' , $id])->andWhere(['cat'=>$cat['id']])->limit(5)->asArray()->all();
        $num = count($list);
        $list2 = Article::find()->select(['id','title'])->where(['<' ,'id' , $id])->andWhere(['cat'=>$cat['id']])->orderBy("id desc")->limit(10 - $num)->asArray()->all();
        $tmp = array_merge((array)$list , (array)$list2);
        $num = count($tmp);
        if($num > 1){
            $list1 = array_slice($tmp , 0 ,round($num / 2));
            $list2 = array_slice($tmp , round($num / 2));
        }else{
            $list1 = $tmp;
            $list2 = [];
        }
        $next = Article::find()->select(['id','title'])->where(['>' ,'id' , $id])->andWhere(['cat'=>$cat['id']])->limit(1)->asArray()->one();
        $pre = Article::find()->select(['id','title'])->where(['<' ,'id' , $id])->andWhere(['cat'=>$cat['id']])->limit(1)->asArray()->one();
        return $this->render('index',[
            'word' => $article,
            'list1' => $list1,
            'list2' => $list2,
            'next' => $next,
            'pre' => $pre,
            'cat' => $cat,
        ]);
    }

    /**
     * 列表
     */
    public function actionList(){
        $py = \Yii::$app->request->get("cat");
        $cat = Category::findOne(['py'=>$py]);
        if (empty($cat)){
            return $this->redirect(Com::urlCat(2) , 301 );
        }
        $query = Article::find()->where(['cat'=>$cat['id']]);
        $pages = new Pagination(['totalCount' =>$query->count(), 'pageSize' => 20]);

        $list = $query->limit($pages->limit)->offset($pages->offset)->orderBy("id desc")->all();
        return $this->render('list',[
            'cat' => $cat,
            'pages' => $pages,
            'list' => $list,
        ]);
    }
}